package com.ygqh.baby.service.impl;

import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.mapper.YgOrderDetailMapper;
import com.ygqh.baby.model.OrderSkuTaxRates;
import com.ygqh.baby.model.OrderTaxes;
import com.ygqh.baby.model.YgPtSkuInfo;
import com.ygqh.baby.model.YgShoppingCarModel;
import com.ygqh.baby.po.YgOrderDetail;
import com.ygqh.baby.po.YgOrderDetailExample;
import com.ygqh.baby.po.YgOrderDetailExample.Criteria;
import com.ygqh.baby.po.YgOrderOperation;
import com.ygqh.baby.service.YgOrderDetailService;
import com.ygqh.baby.service.YgOrderOperationService;
import com.ygqh.baby.service.YgShoppingCarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class YgOrderDetailServiceImpl implements YgOrderDetailService {

    @Autowired
    private YgOrderDetailMapper ygOrderDetailMapper;
    @Autowired
    private YgOrderOperationService ygOrderOperationService;
    @Autowired
    private YgShoppingCarService ygShoppingCarService;

    @Override
    public List<YgOrderDetail> find() {
        YgOrderDetailExample example = new YgOrderDetailExample();
        example.createCriteria();
        return ygOrderDetailMapper.selectByExample(example);
    }

    @Override
    public int findCount() {
        YgOrderDetailExample example = new YgOrderDetailExample();
        example.createCriteria();
        return ygOrderDetailMapper.countByExample(example);
    }

    @Override
    public YgOrderDetail findById(Long id) {
        return ygOrderDetailMapper.selectByPrimaryKey(id);
    }

    @Override
    public int save(YgOrderDetail ygOrderDetail) {
        return ygOrderDetailMapper.insertSelective(ygOrderDetail);
    }

    @Override
    public int update(YgOrderDetail ygOrderDetail) {
        return ygOrderDetailMapper.updateByPrimaryKeySelective(ygOrderDetail);
    }

    @Override
    public ResultSet<YgOrderDetail> search(QueryInfo queryInfo, String q) {
        List<YgOrderDetail> list = ygOrderDetailMapper.selectSuper(queryInfo, q);
        int count = ygOrderDetailMapper.countSuper(q);
        ResultSet<YgOrderDetail> resultSet = new ResultSet<YgOrderDetail>(count, list);
        return resultSet;
    }

    @Override
    public int saveOrUpdate(YgOrderDetail ygOrderDetail) {
        int r = 0;
        if (ygOrderDetail.getId() != null) {
            r = this.update(ygOrderDetail);
        } else {
            r = this.save(ygOrderDetail);
        }
        return r;
    }

    @Override
    public int updateDetailSendBatch(List<YgOrderDetail> detailList) {
        if (CollectionUtils.isEmpty(detailList)) {
            return 0;
        }
        return ygOrderDetailMapper.updateDetailSendBatch(detailList);
    }

    @Override
    public List<YgOrderDetail> findAudited(Long orderId) {
        YgOrderDetailExample example = new YgOrderDetailExample();
        List<String> detailStatus = new ArrayList<String>();
        detailStatus.add(OrderDetailStatus.Audited.name());
        detailStatus.add(OrderDetailStatus.WaitingSign.name());
        example.createCriteria().andOrderIdEqualTo(orderId).andDetailStatusIn(detailStatus);
        return ygOrderDetailMapper.selectByExample(example);
    }

    @Override
    public List<YgOrderDetail> findByOrderId(Long orderId) {
        YgOrderDetailExample example = new YgOrderDetailExample();
        example.createCriteria().andOrderIdEqualTo(orderId);
        return ygOrderDetailMapper.selectByExample(example);
    }

    @Override
    public int addBatch(List<YgOrderDetail> detailList) {
        if (CollectionUtils.isEmpty(detailList)) {
            return 0;
        }
        return ygOrderDetailMapper.insertBatch(detailList);
    }

    @Override
    public int updateRefundStatusByReturn(Long orderId, RefundStatus refundStatus, List<Long> skuIds) {
        YgOrderDetailExample example = new YgOrderDetailExample();
        Criteria criteria = example.createCriteria().andOrderIdEqualTo(orderId);
        if (!CollectionUtils.isEmpty(skuIds)) {
            criteria.andSkuIdIn(skuIds);
        }
        YgOrderDetail detail = new YgOrderDetail();
        detail.setRefundStatus(refundStatus);
        return ygOrderDetailMapper.updateByExampleSelective(detail, example);
    }

    @Override
    public int updateRefundStatusByReturn(Long orderId, ReturnType returnType, ReturnStatus returnStatus, Boolean isSend, List<Long> skuIds) {
        YgOrderDetailExample example = new YgOrderDetailExample();
        Criteria criteria = example.createCriteria().andOrderIdEqualTo(orderId);
        if (!CollectionUtils.isEmpty(skuIds)) {
            criteria.andSkuIdIn(skuIds);
        }
        List<YgOrderDetail> detailList = ygOrderDetailMapper.selectByExample(example);

        for (YgOrderDetail detail : detailList) {
            RefundStatus refundStatus = RefundStatus.ApplyRefund;

            if (!isSend && returnType.equals(ReturnType.Return) && returnStatus.equals(ReturnStatus.WaitingCheck)) {
                // 售前退货审核通过，更新发货标记
                detail.setSendMark("1");
            }
            if (returnType.equals(ReturnType.Return) && (returnStatus.equals(ReturnStatus.Cancel) || returnStatus.equals(ReturnStatus.Reject))) {
                // 取消退货将发货标记设置为null
                if (StringUtil.isNotBlank(detail.getSendMark()) && detail.getSendMark().equals("1")) {
                    detail.setSendMark(null);
                }
            }

            if (!isSend && returnType.equals(ReturnType.Change)) {
                // 售前换货，退款状态直接成功
                refundStatus = RefundStatus.RefundSuccess;
            }
            detail.setRefundStatus(refundStatus);
        }

        return ygOrderDetailMapper.updateRefundStatusByReturn(detailList);

    }

    @Override
    public Message modifyDetail(Long detailId, Long userId, List<YgPtSkuInfo> skuList, String operator) {
        YgOrderDetail detail = this.findById(detailId);
        List<YgShoppingCarModel> carList = ygShoppingCarService.findItemInfoPt(skuList, userId);

        Message message = this.checkModifyDetail(detail, carList);
        if (message.getType().equals(Message.Type.error)) {
            return message;
        }

        List<YgOrderDetail> newList = new ArrayList<YgOrderDetail>();
        StringBuilder skuIds = new StringBuilder();
        StringBuilder productNames = new StringBuilder();
        for (int i = 0; i < carList.size(); i++) {
            YgShoppingCarModel car = carList.get(i);
            skuIds.append(car.getSkuId()).append(",");
            productNames.append(car.getProductName()).append(" ").append(car.getSizeName()).append(",");
            YgOrderDetail clone = detail.clone();
            clone.setSkuCode(car.getSkuCode());
            clone.setSalePrice(car.getSalesPrice());
            clone.setQuantity(car.getQuantity());
            clone.setSize(car.getSizeName());
            if (i == 0) {
                clone.setSkuId(car.getSkuId());
                this.update(clone);
            } else {
                clone.setId(null);
                newList.add(clone);

            }
        }

        this.addBatch(newList);
        YgOrderOperation ygOrderOperation = new YgOrderOperation();
        ygOrderOperation.setOrderId(detail.getOrderId());
        ygOrderOperation.setUserId(userId);
        ygOrderOperation.setSourceSkuId(detail.getSkuId());
        ygOrderOperation.setSkuIds(skuIds.toString().substring(0, skuIds.length() - 1));
        ygOrderOperation.setOperationType(OrderOperation.MofidyDetail);
        ygOrderOperation.setRemark(
                "商品： " + detail.getProductName() + " " + detail.getSize() + " 修改成  " + productNames.toString().substring(0, productNames.length() - 1));
        ygOrderOperation.setCreateBy(operator);
        ygOrderOperation.setCreateTime(new Date());
        ygOrderOperationService.save(ygOrderOperation);
        return message;
    }

    private Message checkModifyDetail(YgOrderDetail detail, List<YgShoppingCarModel> carList) {
        BigDecimal sourcePrice = detail.getSalePrice().multiply(new BigDecimal(detail.getQuantity()));
        BigDecimal newPrice = new BigDecimal(0);
        for (YgShoppingCarModel car : carList) {
            if (detail.getSkuCode().equals(car.getSkuCode())) {
                return Message.error("修改后的商品不能跟原商品一样", detail.getSkuCode());
            }
            BigDecimal price = car.getSalesPrice().multiply(new BigDecimal(car.getQuantity()));
            newPrice = newPrice.add(price);
        }
        if (newPrice.compareTo(sourcePrice) != 0) {
            return Message.error("修改前后价格不一致", newPrice);
        }
        return Message.success(null);

    }

    @Override
    public int cancelRefundMarkByOids(List<Long> oIds) {
        if (CollectionUtils.isEmpty(oIds)) {
            return 0;
        }
        return ygOrderDetailMapper.cancelRefundMarkByOids(oIds);
    }


    @Override
    public List<Map<String, Object>> exportOrderByProductId(Date startDate,
                                                            Date endDate, String q, String platformNo) {
        return ygOrderDetailMapper.selectOrderByProductId(startDate, endDate, q, platformNo);
    }

    @Override
    public Message updateDetailSupplierId(Long[] productIds, Long supplierId) {
        ygOrderDetailMapper.updateDetailSupplierId(productIds, supplierId);

        return Message.success(null);
    }

    @Override
    public List<YgOrderDetail> findByOrderIds(Long[] orderIds) {
        return ygOrderDetailMapper.selectByOrderIds(orderIds);
    }

    @Override
    public int updateRefundStatusById(List<Long> idList, RefundStatus refundStatus) {
        if (CollectionUtils.isEmpty(idList)) {
            return 0;
        }
        return ygOrderDetailMapper.updateRefundStatusById(idList, refundStatus);
    }

    @Override
    public List<OrderSkuTaxRates> getOrderSkuTaxRates(Long orderId) {
        return ygOrderDetailMapper.getOrderSkuTaxRates(orderId);
    }

    @Override
    public OrderTaxes getOrderTaxes(Long orderId) {
        List<OrderSkuTaxRates> orderSkuTaxRates = this.getOrderSkuTaxRates(orderId);
        return this.getOrderTaxes(orderId, orderSkuTaxRates);
    }

    @Override
    public OrderTaxes getOrderTaxes(Long orderId, List<OrderSkuTaxRates> orderSkuTaxRates) {

        BigDecimal valueAddedTax = BigDecimal.ZERO;
        BigDecimal saleTax = BigDecimal.ZERO;
        BigDecimal tariff = BigDecimal.ZERO;
        for (OrderSkuTaxRates orderSkuTaxRate : orderSkuTaxRates) {

            BigDecimal qDecimal = new BigDecimal(orderSkuTaxRate.getQuantity());
            //商品总金额（完税价格）
//			BigDecimal productPrice = orderSkuTaxRate.getSalePrice().multiply(new BigDecimal(orderSkuTaxRate.getQuantity()));
//			BigDecimal subTariff = productPrice.multiply(orderSkuTaxRate.getTariffRate()).setScale(2, BigDecimal.ROUND_HALF_DOWN);
//			//应征消费税税额= (（完税价格+关税税额）/(1-消费税税率)) * 消费税税率
//			BigDecimal subSaleTax = (productPrice.add(subTariff)).divide(BigDecimal.ONE.subtract(orderSkuTaxRate.getSaleTaxRate()),2,BigDecimal.ROUND_HALF_DOWN).multiply(orderSkuTaxRate.getSaleTaxRate());
//			//增值税= （关税完税价格+关税+消费税）* 增值税税率
//			BigDecimal subValueAddedTax = (productPrice.add(subTariff).add(subSaleTax)).multiply(orderSkuTaxRate.getTariffRate()).setScale(2, BigDecimal.ROUND_HALF_DOWN);
            valueAddedTax = valueAddedTax.add(orderSkuTaxRate.getSingleValueAddedTax().multiply(qDecimal));
            saleTax = saleTax.add(orderSkuTaxRate.getSingleSaleTax().multiply(qDecimal));
            tariff = tariff.add(orderSkuTaxRate.getSingleTariff().multiply(qDecimal));
        }
        OrderTaxes orderTaxes = new OrderTaxes();
        orderTaxes.setOrderId(orderId);
        orderTaxes.setSaleTax(saleTax);
        orderTaxes.setTariff(tariff);
        orderTaxes.setValueAddedTax(valueAddedTax);
        return orderTaxes;
    }

    @Override
    public Boolean existSupplierGoods(Long orderId, Long supplierId) {
        return ygOrderDetailMapper.existSupplierGoods(orderId, supplierId);
    }

    @Override
    public int getAlreadyPushWdtTimes(Long orderId) {
        return ygOrderDetailMapper.getAlreadyPushWdtTimes(orderId);
    }

    @Override
    public List<YgOrderDetail> findDetailsBySupplierId(Long orderId, Long supplierId) {
        Assert.notNull(supplierId, "supplierId can't be null");
        YgOrderDetailExample example = new YgOrderDetailExample();
        Criteria criteria = example.createCriteria();
        if (orderId != null) {
            criteria.andOrderIdEqualTo(orderId);
        }
        criteria.andSupplierIdEqualTo(supplierId);
        return ygOrderDetailMapper.selectByExample(example);
    }

    @Override
    public List<YgOrderDetail> findByOutCode(String outCode) {
        Assert.notNull(outCode, "outCode can't be null");
        YgOrderDetailExample example = new YgOrderDetailExample();
        example.createCriteria().andOutCodeEqualTo(outCode);
        return ygOrderDetailMapper.selectByExample(example);
    }


}
